from django.shortcuts import render, redirect
from polls.models import Question

# 用户发来的请求，将会作为第一个参数传给函数，所以需要用一个变量来接收
def index(request):
    questions = Question.objects.order_by('-pub_date')
    # 通过render函数找到名为index.html的模板文件，返回给用户
    return render(request, 'index.html', {'questions': questions})

def detail(request, q_id):
    # url上的数字，将会作为参数传递给q_id
    question = Question.objects.get(id=q_id)
    # 字典内容将会以key=val的形式传给detail.html，detail.html就可以拥有变量了
    return render(request, 'detail.html', {'question': question})

def result(request, q_id):
    question = Question.objects.get(id=q_id)
    return render(request, 'result.html', {'question': question})

def vote(request, q_id):
    question = Question.objects.get(id=q_id)  # 取出给哪个问题投票
    # 在用于请求的POST对象中取出c_id的值。POST是一个字典，通过get方法取值
    c_id = request.POST.get('c_id')
    if c_id:  # 如果c_id不为空，取出具体的选项，将其票数加1
        choice = question.choice_set.get(id=c_id)
        choice.votes += 1
        choice.save()

    # 投票完成后，跳转到result结果页
    return redirect('result', q_id)
